<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :destroy-on-close="close_modal_destroy"
    :close-on-click-modal="close_modal"
    @close="handleCancel"
    width="1000px"
    append-to-body
  >
    <!--
            @save: 按下 ctrl + s 时触发
            @change: 当值发生改变时 触发
        -->
    <mavon-editor
      @save="saveDoc"
      ref="editor"
      @imgAdd="imgAdd"
      @change="changeMavon"
      v-model="doc">
    </mavon-editor>
  </el-dialog>
</template>

<script>
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";
import {addShare, closeSave, save, updateLivingMinio, upImage} from "@/api/liveShare";
export default {
  name: "addLifeShare",
  components: { mavonEditor },
  data() {
    return {
      title: '发布你的健康生活',
      visible: false,
      close_modal_destroy: true,
      close_modal: false,
      doc: "",
      id: undefined,
      htmlContext: ''
    }
  },
  methods: {
    add() {
      this.title = '发布你的健康生活'
      this.visible = true
      addShare().then(res => {
        if (res.body.data == -1)
          this.$message.error("id分配错误")
        this.id = res.body.data
      })
      this.doc = ""
    },
    handleCancel() {
      this.close()
    },
    async close() {
      var updateShare = {
        id: this.id,
        context: this.htmlContext
      }
      await closeSave(updateShare).then(res => {
        if (res.body.data) {
          this.$message.success("保存成功")
          this.$emit('ok')
        }
        else
          this.$message.error("错误保存")
      })
      this.$emit('close')
      this.visible = false
    },
    changeMavon(markdown, html) {
      this.htmlContext = html
    },
    saveDoc(markdown, html) {
      // 此时会自动将 markdown 和 html 传递到这个方法中
      var updateShare = {
        id: this.id,
        context: html
      }
      save(updateShare).then(res => {
        if (res.body.data)
          this.$message.success("保存成功")
        else
          this.$message.error("重新保存")
      })
    },
    async imgAdd(pos, $file) {
      let formdata = new FormData()
      var imageUrl = ''
      formdata.append('file',$file)
      await upImage(formdata).then(res => {
        this.$refs.editor.$img2Url(pos, res.body.data)
        imageUrl = res.body.data
      })
      updateLivingMinio(this.id, imageUrl).then(res => {
        if (res.body.data)
          this.$message.success("上传成功")
        else
          this.$message.error("上传失败")
      })
    }
  }
}
</script>

<style scoped>

</style>
